package java2023.juc.com;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author: wz
 * @Date: 2023/3/9 11:40
 * @Description: 线程池核心点： 复用机制 ------
 * 1. 提前创建好固定的线程一直在运行状态----死循环实现
 * 2. 提交的线程任务缓存到一个并发队列集合中， 交给我们正在运行的线程执行
 * 3. 正在运行的线程就从队列中获取该任务执行
 * <p>
 * 手写线程池
 */
public class MyExecutors {

    public BlockingDeque<Runnable> runnables;
    private volatile Boolean isRun = true;


    /**
     * dequeSize 缓存任务大小
     *
     * @param dequeSize
     * @param threadCount 复用线程池
     */
    public MyExecutors(int dequeSize, int threadCount) {
        runnables = new LinkedBlockingDeque<>(dequeSize);
        for (int i = 0; i < threadCount; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
        }
    }
    public void execute(Runnable runnable) {
        runnables.offer(runnable);
    }

    class WorkThread extends Thread {
        @Override
        public void run() {
            while (isRun || runnables.size() > 0) {
                Runnable runnable = runnables.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    public static void main(String[] args) {
        MyExecutors myExecutors = new MyExecutors(10, 2);
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            myExecutors.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":," + finalI);
                }
            });
        }
        myExecutors.isRun = false;
    }
}



